import React, { useEffect, useMemo, useState } from 'react';
import { Image, View } from '@tarojs/components';
import './index.less';
import store from '@/src/store';
import Taro, { useDidShow } from '@tarojs/taro';
import { mineCollect, mineContent } from '@/src/common/util/contant';
import { observer } from 'mobx-react-lite';
import { userInfoFun } from '@/src/common/method/loginFun';
import {
  feature,
  getRandomCombination,
  identity,
  sence,
} from '@/src/utils/commonFun';
import { getNetWorkStatus } from '@/src/common/util/util';
import { netWorkErrorInfo } from '@/src/utils/constants';
import { shopCigarCabinetFun } from '@/src/common/method/homeFun';
import { halfScreenJump } from '@/src/utils/halfScreen';
import { userSearchListFun } from '@/src/common/method/homeSearchFun';
import { isLoginFun } from '@/src/common/method/commonFun';
//我的主页面
const Mine = () => {
  const [login, setLogin] = useState(true); //是否登录
  const [data, setData] = useState<any>([]);
  const [nickname, setNickname] = useState<any>('');
  const [pagePath, setPagePath] = useState<string>('');
  const [userDataList, setUserDataList] = useState<any>([]); //搜索列表
  const getUserInfo = () => {
    const userId = Taro.getStorageSync('userId');
    userInfoFun({
      access_token: Taro.getStorageSync('access_token_login'),
    }).then((res: any) => {
      setData(res);
      Taro.setStorageSync('avatarUrl', res.avatarUrl);
      if (res?.nickname) {
        setNickname(res.nickname); // 更新视图
        Taro.setStorageSync(`nickname-${userId}`, res.nickname); // 同步缓存，确保返回后也能立刻显示
      }
    });
  };

  const shopCigarCabinet = () => {
    const data = {
      pageType: 'MY_ORDER_PAGE',
    };
    shopCigarCabinetFun(data)
      .then((res: any) => {
        console.log(res, 'shopCigarCabinet-fun-res');
        setPagePath(res.pagePath);
      })
      .catch(() => {});
  };

  useDidShow(() => {
    //获取网络状态
    Taro.onNetworkStatusChange(getNetWorkStatus);
    // 同步登录态
    const token = Taro.getStorageSync('access_token_login');
    setLogin(!!token);
    const userId = Taro.getStorageSync('userId');
    // 先用本地缓存立刻更新 UI（保证返回后立即看到新昵称）
    const cacheNick = Taro.getStorageSync(`nickname-${userId}`);
    if (cacheNick) setNickname(cacheNick);

    // 再请求服务端，确保与后端一致
    getUserInfo();
  });
  useEffect(() => {
    // 同步登录态
    setLogin(!!Taro.getStorageSync('access_token_login'));
    const userId = Taro.getStorageSync('userId');
    // 昵称：有缓存先用缓存；没有就生成随机；然后拉取后端覆盖
    const cacheNick = Taro.getStorageSync(`nickname-${userId}`);
    if (cacheNick === '' || cacheNick === null) {
      const nick: any = getRandomCombination(feature, identity, sence, '');
      Taro.setStorageSync(`nickname-${userId}`, nick);
      setNickname(nick);
    } else {
      setNickname(cacheNick);
    }

    getUserInfo();

    //查询商城半屏跳转地址的方法
    shopCigarCabinet();
  }, []);

  //跳转到退出账号页面
  const handleExitClick = () => {
    //判断网络状态，如果没有网络则不可点击
    if (!store.commonStore.networkStatus) {
      Taro.showToast({ title: netWorkErrorInfo, icon: 'none' });
      return;
    }
    if (!isLoginFun()) return;
    Taro.navigateTo({
      url: '/subPagesMine/exitAccount/index',
    });
  };

  //跳转到登录
  const getoLogin = () => {
    //判断网络状态，如果没有网络则不可点击
    if (!store.commonStore.networkStatus) {
      Taro.showToast({ title: netWorkErrorInfo, icon: 'none' });
      return;
    }
    Taro.navigateTo({ url: '/subPagesAuth/login/index' });
  };
  //跳转到收藏/常用功能详情页
  const gotoDetail = async (url: any, id: number = 0) => {
    //判断网络状态，如果没有网络则不可点击
    if (!store.commonStore.networkStatus) {
      Taro.showToast({ title: netWorkErrorInfo, icon: 'none' });
      return;
    }
    if (!isLoginFun()) return;
    if (id === 2) {
      if (pagePath === '') {
        Taro.showToast({ title: '暂无订单，请稍后查询。', icon: 'none' });
        return;
      }
      halfScreenJump(pagePath, {
        onFail: (err) => {
          //打开失败回调
          Taro.showToast({
            title: '暂无订单，请稍后查询。',
            icon: 'none',
          });
        },
        onReturn: ({ reason, extraData }) => {
          //关闭半屏回调
          console.log('return reason:', reason, extraData);
        },
      });
    } else {
      Taro.navigateTo({ url: url });
    }
  };
  useEffect(() => {
    //用户搜索
    console.log(data.nickname, '===用户搜索结果44');
    userSearchListFun({
      searchWords: data.nickname,
      pageNo: 1,
      pageSize: 10,
    }).then((res: any) => {
      console.log(res, '===用户搜索结果33');
      let result: any = [];
      setUserDataList([res.list]);
    });
  }, [data]);

  const getImageSrc = useMemo(() => {
    switch (userDataList.tag) {
      case '品牌方':
        return require('../../assert/imgs/user/pinpai.png');
      case '大咖':
        return require('../../assert/imgs/user/daka.png');
      case '雪茄吧':
        return require('../../assert/imgs/user/xuejiaba.png');
      case '侍咖师':
        return require('../../assert/imgs/user/shikashi.png');
      default: // 包括 null 的情况
        return null;
    }
  }, [userDataList]);
  return (
    <View
      className="home-mine"
      style={{
        paddingTop: `calc(${store.commonStore.safeAreaTop}rpx + 88rpx)`,
        height: `calc(100vh - ${store.commonStore.safeAreaTop}rpx - 88rpx)`,
      }}
    >
      {login ? (
        <View className="home-mine-logined" onClick={() => handleExitClick()}>
          <View className="login-avator">
            <Image src={data.avatarUrl} />
          </View>
          <View className="login-immediate">
            <View className="user-center-name">
              {nickname.slice(0,10)}

              <Image className="brand-icon" src={getImageSrc} />
              {/* <Text className="brand-name">高希霸品牌</Text> */}
            </View>
            <View className="user-center-account">账号：{data.username}</View>
            <View className="user-center-account">
              IP属地：{store.commonStore.province}
            </View>
          </View>
          <View className="login-more">
            <Image
              src={
                'https://file.linkcook.cn/image/wineMiniProgram/mine/more.png'
              }
            />
          </View>
        </View>
      ) : (
        <View className="home-mine-login" onClick={() => getoLogin()}>
          <View className="login-avator" onClick={() => handleExitClick()}>
            <Image
              src={
                'https://file.linkcook.cn/image/wineMiniProgram/mine/default.png'
              }
            />
          </View>
          <View className="login-immediate">
            <View className="login-btn">
              立即登录
            </View>
            <View className="login-desc">登录后体验更多功能哦~</View>
          </View>
          <View className="login-more">
            <Image
              src={
                'https://file.linkcook.cn/image/wineMiniProgram/mine/more.png'
              }
            />
          </View>
        </View>
      )}

      <View className="home-mine-content">
        {/* 常用功能 */}
        <View className="content">
          <View className="title">常用功能</View>
          <View className="home-mine-item">
            {mineContent.map((item: any) => {
              return (
                <View
                  key={item.id}
                  className="item-list"
                  onClick={() => gotoDetail(item.url, item.id)}
                >
                  <Image src={item.image} />
                  <View className="desc">{item.title}</View>
                </View>
              );
            })}
          </View>
        </View>

        {/* 其他功能 */}
        <View className="content">
          <View className="title">我的收藏</View>
          <View className="home-mine-item">
            {mineCollect.map((item: any, index: any) => {
              return (
                <View
                  key={index}
                  className="item-list"
                  onClick={() => gotoDetail(item.url)}
                >
                  <Image src={item.image} />
                  <View className="desc">{item.title}</View>
                </View>
              );
            })}
          </View>
        </View>
      </View>
    </View>
  );
};

export default observer(Mine);
